package com.hllxd.hism.star.basic.service.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hllxd.hism.star.basic.service.collect.DateUtils;
import com.hllxd.hism.star.basic.service.dao.ck.UserTraceMapper;
import com.hllxd.hism.star.basic.service.dao.mapper.doris.DictCmcMapper;
import com.hllxd.hism.star.basic.service.dao.mapper.mis.ZpBiDimEnumMapper;
import com.hllxd.hism.star.basic.service.model.UserTrace;
import com.hllxd.hism.star.basic.service.model.doris.DictCmcEntity;
import com.hllxd.hism.star.basic.service.util.Utils;
import com.hllxd.hism.star.basic.service.constant.Constants;
import com.hllxd.hism.star.basic.service.model.TraceImc;
import com.hllxd.hism.star.basic.service.model.TraceImcTags;
import com.hllxd.hism.star.basic.service.model.ZpBiDimEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yaofangjun
 * @date 2023/2/13 14:48
 * https://docs.58corp.com/#/space/1619177925616140290
 */
@Slf4j
@Service("userTraceService")
public class UserTraceServiceImpl implements UserTraceService {

    @Autowired
    private UserTraceMapper userTraceMapper;

    @Autowired
    private DictCmcMapper dictCmcMapper;

    @Autowired
    private ZpBiDimEnumMapper zpBiDimEnumMapper;


    private final static int IMC_SCF_MAX = 1000;
    private final static String DEFAULT_INVALID = "0";
    @Override
    public List<UserTrace> findUserTrace(String ts1, String ts2, String userId, Boolean hasExp) {

        List<UserTrace> userTraces = userTraceMapper.findUserTrace(ts1, ts2, userId, hasExp);
        log.info("userId: {}, query count: {}", userId, userTraces.size());
        if(userTraces.size()==0) {
            log.info("query is empty.");
            return userTraces;
        }
        //路飞中平台类型的dim_id=2
        HashMap<String, String> platformMap = getDimInfoMap(2);
        //路飞中商业类型的dim_id=7
        HashMap<String, String> adDispTypeMap = getDimInfoMap(7);
        //路飞中slot的dim_id=3
        HashMap<String, String> slotInfoMap = getDimInfoMap(3);
        HashMap<Long, String> imcMap = new HashMap<>();
        int currCnt = 0;
        for (UserTrace userTrace : userTraces) {
            userTrace.optTypeName = Constants.TABLE_BEHAVIOR_MAP.get(userTrace.getTableName());
            userTrace.setPlatform(platformMap.getOrDefault(userTrace.getPlatform(), userTrace.getPlatform()));
            userTrace.requestTypeName = adDispTypeMap.getOrDefault(userTrace.getAdDispType(), userTrace.getAdDispType());
            userTrace.slotName = slotInfoMap.getOrDefault(userTrace.getSlot(), userTrace.getSlot());
            Long adId = userTrace.getAdId();
            if (imcMap.containsKey(adId)) {
                userTrace.setTitle(imcMap.get(adId));
            } else {
                String title = "-";
                if(++currCnt<IMC_SCF_MAX) {
                    // 限制访问SCF的次数
                    title = "info title";//ScfUtil.getInfoTitle(adId);
                }
                userTrace.setTitle(title);
                imcMap.put(adId, title);
            }
        }
        log.info("result size: {}",userTraces.size());
        return userTraces;
    }



    public HashMap<String, String> getDimInfoMap(Integer dimId) {
        List<ZpBiDimEnum> zpBiDimEnums = zpBiDimEnumMapper.findByDimId(dimId);
        HashMap<String, String> dict = new HashMap<>();
        for (ZpBiDimEnum zpBiDimEnum : zpBiDimEnums) {
            dict.put(zpBiDimEnum.getEnumValue(), zpBiDimEnum.getEnumName());
        }
        return dict;
    }

    @Override
    public List<TraceImc> findTraceImc(String ts1, String ts2, String infoId, Boolean hasExp) {
        List<TraceImc> userTraces = userTraceMapper.findTraceImc(ts1, ts2, infoId, hasExp);
        log.info("info: {}, query count: {}", infoId, userTraces.size());
        //路飞中平台类型的dim_id=2
        HashMap<String, String> platformMap = getDimInfoMap(2);
        //路飞中商业类型的dim_id=7
        HashMap<String, String> adDispTypeMap = getDimInfoMap(7);
        //路飞中slot的dim_id=3
        HashMap<String, String> slotInfoMap = getDimInfoMap(3);

        Map<Long,String> localMap = loadLocalMap();

        int currCnt = 0;
        HashMap<Long, String> userMap = new HashMap<>();
        for (TraceImc it : userTraces) {
            it.optTypeName = Constants.TABLE_BEHAVIOR_MAP.get(it.getTableName());
            it.platform = platformMap.getOrDefault(it.getPlatform(), it.getPlatform());
            it.requestTypeName = adDispTypeMap.getOrDefault(it.getAdDispType(), it.getAdDispType());
            it.slotName = slotInfoMap.getOrDefault(it.getSlot(), it.getSlot());
            it.dispLocal1Name = localMap.get(Utils.toLong(it.dispLocal1));
            it.pid = readPidTime(it.tjfrom);
            Long userId = Long.valueOf(it.userId);
            if (userMap.containsKey(userId)) {
                it.userName = userMap.get(userId);
            } else {
                String title = "-";
//                if(++currCnt<IMC_SCF_MAX) {
//                    // 限制访问SCF的次数
//                    try {
//                        title = ScfUtil.getUserResume(userId);
//                    }catch (Exception e) {
//                        log.warn("ScfUtil.getUserResume exception.{}",e.toString());
//                    }
//                }
                it.userName = title;
                userMap.put(userId, title);
            }
        }
        log.info("result size: {}",userTraces.size());
        return userTraces;
    }

    static private String pid2ts(Long pid) {
        if (pid == null || pid<= 0L) {
            return null;
        }
        long createTimeStamp = ( pid >> 22 ) + 1551369600000L;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(createTimeStamp);
    }

    private String readPidTime(String tjfrom) {
        if(StringUtils.isEmpty(tjfrom) || tjfrom.length()<8) {
            return null;
        }
        try {
            JSONObject json = JSON.parseObject(tjfrom);
            Long pid = json.getLong("pid");
            return pid2ts(pid);
        }catch (Exception e) {
            return null;
        }
    }
    @Override
    public TraceImcTags queryTraceImcTags(String infoId) {
        if(infoId==null || infoId.equals(DEFAULT_INVALID)) {
            log.info("info id is invalid.");
            return null;
        }
        TraceImcTags tags = new TraceImcTags();
        tags.infoId = infoId;
        try {
            tags.infoTitle = "info title";//;ScfUtil.getInfoTitle(Long.valueOf(infoId));
        }catch (Exception e) {
            log.warn("ScfUtil.getInfoTitle exception. {}",e.toString(), e);
        }
        return tags;
    }

//    @Override
//    public TraceUserTags queryTraceUserTags(String userId) {
//        if(userId==null || userId.equals(DEFAULT_INVALID)) {
//            log.info("user id is invalid.");
//            return null;
//        }
//        log.info("userId: {}.",userId);
//        TraceUserTags tags = new TraceUserTags();
//        tags.userId = userId;
//        try {
//            tags.userName = ScfUtil.getUserResume(Long.valueOf(userId));
//        }catch (Exception e) {
//            log.warn("ScfUtil.getUserResume exception.{}",e.toString(), e);
//        }
//        log.info("user id: {}, name: {}.", userId, tags.userName);
//        return tags;
//    }


    Map<Long,String> loadLocalMap() {

        List<DictCmcEntity> localEntities = dictCmcMapper.listDispLocal1(DateUtils.lastDate(-1));

        Map<Long,String> res = new HashMap<>(localEntities.size());
        for(DictCmcEntity local:localEntities) {
            res.put(Utils.toLong(local.k),local.v);
        }
        return res;
    }

}
